from web.controllers.api import route_api
from common.models.food import Food
from common.models.food import FoodCat
from common.libs.UrlManager import UrlManager
from flask import request, jsonify, g
from common.models.cart import MemberCart
from sqlalchemy import or_

@route_api.route('/food/index')
def FoodIndex():
    res = {'code': 200, 'msg': '操作成功!', 'data': {}}
    food_list = Food.query.filter_by(status=1).order_by \
        (Food.total_count.desc(), Food.id.desc()).limit(3).all()
    banners = []
    for food in food_list:
        data_food = {
            "id": food.id,
            "pic_url": UrlManager.buildImageUrl(food.main_image)
        }
        banners.append(data_food)
    categories = [
        {'id': 0, 'name': "全部"},
    ]
    # 按权重降序
    food_cat_list = FoodCat.query.filter_by(status=1).order_by(FoodCat.weight.desc()).all()
    for food_cat in food_cat_list:
        data_cat = {
            'id': food_cat.id,
            'name': food_cat.name
        }
        categories.append(data_cat)
    res['data']['banners'] = banners
    res['data']['categories'] = categories
    return jsonify(res)

@route_api.route('/food/search')
def FoodSearch():
    res = {'code': 200, 'msg': '操作成功!', 'data': {}}
    resp = request.values
    query = Food.query
    # 分页大小
    page_size = 4
    page = resp.get('page', type=int, default=1)
    offset = (page - 1) * page_size
    goods = []
    # 混合搜索
    if 'mix_kw' in resp:
        rule = or_(
            Food.name.ilike('%{}%'.format(resp['mix_kw'])),
            Food.tags.ilike('%{}%'.format(resp['mix_kw']))
        )
        query = query.filter(rule)

    if 'cat_id' in resp and int(resp['cat_id']) > 0:
        query = query.filter(Food.cat_id == resp['cat_id'])

    food_list = query.filter(Food.status == 1).order_by \
        (Food.total_count.desc(), Food.id.desc()).offset(offset).limit(page_size).all()

    for food in food_list:
        data_food = {
            "id": food.id,
            "name": food.name,
            "min_price": str(food.price),
            "price": str(food.price),
            "pic_url": UrlManager.buildImageUrl(food.main_image)
        }
        goods.append(data_food)
    res['data']['goods'] = goods
    res['data']['has_more'] = 0 if len(food_list) < page_size else 1

    return jsonify(res)

@route_api.route('/food/info')
def FoodInfo():
    res = {'code': 200, 'msg': '操作成功!', 'data': {}}
    resp = request.values
    id = resp.get('id')

    food_info = Food.query.filter_by(id=id).first()
    if not food_info:
        res['code'] = -1
        res['msg'] = '商品已经下架'
        return jsonify(res)

    shopCarNum = 0
    if g.current_member:
        member_id = g.current_member.id
        shopCarNum = MemberCart.query.filter_by(member_id=member_id).count()

    info = {
        "id": food_info.id,
        "name": food_info.name,
        "summary": food_info.summary,
        "total_count": food_info.total_count,
        "comment_count": food_info.comment_count,
        "stock": food_info.stock,
        "price": str(food_info.price),
        "main_image": UrlManager.buildImageUrl(food_info.main_image),
        "pics": [UrlManager.buildImageUrl(food_info.main_image)]
    }

    res['data']['info'] = info
    res['data']['shopCarNum'] = shopCarNum
    return jsonify(res)
